import { getInfo, login, getMenu,validateRole  } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter, constantRoutes } from '@/router'
import Layout from '@/layout'
const getDefaultState = () => {
    return {
        token: getToken(),
        userUid: '',
        nickName: '',
        userName: '',
        avatar: '',
        roles: [],
        routers: [],
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_USERUID: (state, userUid) => {
        state.userUid = userUid
    },
    SET_NICKNAME: (state, nickName) => {
        state.nickName = nickName
    },
    SET_USERNAME: (state, userName) => {
        state.userName = userName
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_ROUTERS: (state, routers) => {
        state.routers = constantRoutes.concat(routers);
    },
}

const actions = { //异步
    // user login
    login({ commit }, userInfo) { //{ commit }相当于是context.commit
        // const username = userInfo.username.trim()
        // const password = userInfo.password.trim()
        // const isRememberMe = userInfo.isRememberMe;
        return new Promise((resolve, reject) => {
            // var params = new URLSearchParams() //username=**&password=**
            // params.append('username', username)
            // params.append('password', password)
            // params.append('isRememberMe', isRememberMe)
            login({email: userInfo.username.trim(),password: userInfo.password.trim()}).then(response => {
                const { data } = response
                if(data.code !== 200){
                  alert(data.msg)
                  resolve()
                }
                // commit('SET_TOKEN', data.token)
                setToken(data.data.token)
                commit('SET_TOKEN', getToken())
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(response => {
                const { data } = response
                if (validateRole(data.data.roleList)) { // 验证返回的roles是否是一个非空数组
                    commit('SET_ROLES', data.data.roleList)
                } else {
                    reject('getInfo: roles must be a non-null array !')
                }
                commit('SET_USERUID', data.data.id)
                commit('SET_NICKNAME', data.data.username)
                commit('SET_USERNAME', data.data.email)
                commit('SET_AVATAR', data.data.headUrl)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },



    // 获取菜单列表
    getMenu({ commit }) {
        return new Promise((resolve, reject) => {
            getMenu().then(response => {
                let routes = [];
                generaMenu(routes, response.data.data);
                commit('SET_ROUTERS', routes);
                resolve(response)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}


export function generaMenu(routes, data) {
    data.forEach(item => {
        const menu = {
            path: item.path,
            component: item.component === 'Layout' ? Layout : (resolve) => { require(['@/views' + item.component], resolve) },
            redirect: item.redirect,
            hidden: item.hidden === 1 ? true : false,
            children: [],
            name: item.name,
            meta: item.meta
        }
        if (item.children) {
            generaMenu(menu.children, item.children)
        }
        routes.push(menu)
    })
    let error = { path: '*', redirect: '/404', hidden: true }
    routes.push(error)
}
